<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog=true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column label="角色" align="center" width="200" prop="name">
        <template v-slot="{row}">
          <!-- 条件判断 -->
          <el-input v-if="row.isEdit" size="mini" v-model="row.editRow.name"/>
          <span v-else>{{ row.name }}</span>
        </template>
        </el-table-column>
        <el-table-column label="启用" align="center" width="200" prop="state">
          <!-- 自定义列结构 -->
          <template v-slot="{row}">
            <!-- 开 1 关 0 -->
          <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0"/>
          <span v-else>{{ row.state  === 1 ? '已启用' : row.state === 0 ? '未启用' : '无'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center" prop="description">
          <template v-slot="{row}">
          <el-input v-if="row.isEdit" size="mini" type="textarea" v-model="row.editRow.description"></el-input>
        <span v-else>{{ row.description }}</span>
        </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <!-- 放置操作按钮 -->
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button size="mini" type="primary" @click="btnEditOk(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
           <template v-else>
            <!-- 非编辑状态 -->
            <el-button type="text" size="mini" @click="btnPermission(row.id)">分配权限</el-button>
            <el-button type="text" size="mini" @click="btnEditRow(row)">编辑</el-button>
            <el-popconfirm
                title="这是一段内容确定删除吗？"
                @confirm="confirmDel(row.id)"
              >
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
           </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置一个分页组件 -->
      <el-row type="flex" justify="end" style="height:60px;" align="middle">
        <!-- 放置分页组件 -->
        <el-pagination
        :page-size="pageParams.pagesize"
        :current-page="pageParams.page"
        :total="pageParams.total"
        @current-change="changePage"
        layout="prev,pager,next"/>
      </el-row>
    </div>
    <!-- 放置弹层 -->
    <el-dialog @close="btnCancel" :visible.sync="showDialog" title="新增角色" width="500px" >
      <!-- 表单内容 -->
      <el-form label-width="120px" :model="roleForm" :rules="rules" ref="roleForm">
        <el-form-item label="角色名称" prop="name">
          <el-input size="mini" style="width:300px" v-model="roleForm.name"/>
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <!-- 重置表单数据 需要prop属性 -->
          <!-- 如果不需要校验 就不需要写prop属性 -->
          <el-switch size="mini" v-model="roleForm.state"  :active-value="1" :inactive-value="0"/>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input type="textarea" :rows="3" size="mini" style="width:300px" v-model="roleForm.description"/>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button size="mini" type="primary" @click="btnOK">确认</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 放置权限弹窗 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <el-tree check-strictly ref="permTree" node-key="id" :data="permissionData" :props="{label:'name'}" show-checkbox default-expand-all :default-checked-keys="permIds"/>
      <el-row type="flex" justify="center" slot="footer">
        <el-col :span="6">
        <el-button size="mini" type="primary" @click="btnPermissionOK">确定</el-button>
        <el-button size="mini" @click="showPermissionDialog=false">取消</el-button>
      </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import {getRoleList,addRole,updateRole,delRole,getRoleDetail,assignPerm} from '@/api/role'
import {getPrimissionList} from '@/api/permission'
import {transListToTreeData} from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      list:[],
      showDialog:false, //控制弹层显示隐藏
      // 将分页信息放置到一个对象中
      pageParams:{
        page:1,  //第几页
        pagesize:5,  //每页多少条
        total:0
      },
      roleForm:{
        name:'',
        description:'',
        state:0  //默认未启用   关闭 0  打开 1 
      }, 
      rules:{
        name:[{required:true,message:'角色名称不能为空',trigger:'blur'}],
        description:[{required:true,message:'角色描述不能为空',trigger:'blur'}]

      },
      showPermissionDialog:false,
      permissionData:[],
      currentRoleId:null,
      permIds:[]
    }
  },
  created() {
    this.getRoleList()
  },
  methods:{
    async getRoleList() {
      const{rows,total} =await getRoleList(this.pageParams)
      this.list = rows //赋值数据
      this.pageParams.total=total
      // 针对每一行数据添加一个编辑标记
      this.list.forEach(item=>{
        // item.isEdit=false //添加0一个属性  初始值为false
        // 数据响应式的问题 数据变化 视图更新
        // 添加的动态属性 不具备响应式特点
        // this.$set(目标对象，属性名称，初始值) 可以针对目标对象 添加的属性 添加响应式
        this.$set(item,'isEdit',false)
        this.$set(item,'editRow',{
          name:item.name,
          state:item.state,
          description:item.description
        })
      })
    },
    //切换分页时 请求新的数据
    changePage(newPage) {
      this.pageParams.page=newPage //赋值当前页码
      this.getRoleList()
    },
    btnOK() {
      this.$refs.roleForm.validate(async isOK=>{
        if(isOK) {
          await addRole(this.roleForm)
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.btnCancel()
        }
      })
    },
    btnCancel() {
      this.$refs.roleForm.resetFields()  //重置表单数据
      this.showDialog = false  //关闭弹窗
    },
    // 点击editrow
    btnEditRow(row) {
      row.isEdit =true  //改变行的编辑状态
      // 更新缓存数据
      row.editRow.name =row.name
      row.editRow.state =row.state
      row.editRow.description =row.description
    },
    // 点击确定时触发
    async btnEditOk(row) {
      if(row.editRow.name &&row.editRow.description) {
        //下一步操作
        await updateRole({...row.editRow,id:row.id})
        // 更新成功
        this.$message.success('更新角色成功')
        // 更新显示数据  退出编辑状态
        // row.name = row.editRow.name   //eslint 的一个校验 误判
        Object.assign(row,{
          ...row.editRow,
          isEdit:false  //退出编辑模式
        })  //规避eslint的误判
      }else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    async confirmDel(id) {
      
      await delRole(id)  //后端删除
      this.$message.success('删除角色成功')
      // 删除的如果时最后一个
      if(this.list.length === 1) this.pageParams.page--
      this.getRoleList()
    },
    async btnPermission(id) {
      this.permissionData = transListToTreeData(await getPrimissionList(),0)
      this.currentRoleId = id
      const {permIds} = await getRoleDetail(id)
      this.permIds = permIds
      this.showPermissionDialog = true
    }, 
    async btnPermissionOK() {
      await assignPerm({
        id:this.currentRoleId,
        permIds:this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog=false
    } 
  },
  
}
</script>
<style scoped>
.role-operate {
  padding:10px;
}
</style>